package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.PeachblossomVoice;
import com.tanhua.service.PeachblossomVoiceApi;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author げっしょく
 * @date 2021/11/7
 */
@DubboService
public class PeachblossomVoiceApiImpl implements PeachblossomVoiceApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PeachblossomVoice randomVoice() {
        //用户从数据库中随机读取一条数据
        TypedAggregation<PeachblossomVoice> aggregation = Aggregation.newAggregation(PeachblossomVoice.class, Aggregation.sample(1l));
        AggregationResults<PeachblossomVoice> aggregate = mongoTemplate.aggregate(aggregation, PeachblossomVoice.class);
        List<PeachblossomVoice> mappedResults = aggregate.getMappedResults();
        if (CollUtil.isEmpty(mappedResults)) {
            return null;
        }
        PeachblossomVoice peachblossomVoice = mappedResults.get(0);
        Criteria criteria = Criteria.where("voiceUrl").is(peachblossomVoice.getVoiceUrl());
        Query query = Query.query(criteria);
        mongoTemplate.remove(query, PeachblossomVoice.class);
        return peachblossomVoice;

    }

    @Override
    public void saveVoice(PeachblossomVoice p) {
        mongoTemplate.save(p);
    }
}
